package com.crm.smartmachine.ui.receive

import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import androidx.recyclerview.widget.DefaultItemAnimator
import com.cheng.library.common.clickNoRepeat
import com.cheng.library.common.toast
import com.cheng.library.utils.Param
import com.crm.smartmachine.R
import com.crm.smartmachine.base.SmartBaseFragment
import com.crm.smartmachine.contants.EventConstants
import com.crm.smartmachine.databinding.FragmentReceiveBill2Binding
import com.crm.smartmachine.event.Message
import com.crm.smartmachine.manager.ModbusManager
import com.crm.smartmachine.manager.callback.WriteRegistersCallback
import com.crm.smartmachine.ui.dialog.ReceiveSuccessDialog
import com.crm.smartmachine.ui.receive.adapter.BillAdapter
import com.crm.smartmachine.ui.receive.adapter.BillAdapter2
import com.crm.smartmachine.viewmodel.MainViewModel
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.zgkxzx.modbus4And.requset.ModbusReq
import com.zgkxzx.modbus4And.requset.OnRequestBack
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * 申领物品清单
 */
class ReceiveBillFragment2 : SmartBaseFragment<FragmentReceiveBill2Binding>() {

    override fun getLayoutId(): Int? = R.layout.fragment_receive_bill2

//    private val viewModel: MainViewModel by viewModel()

    @Param
    private lateinit var qhm: String

    private val billAdapter by lazy { BillAdapter2() }

    private lateinit var mSoundPool: SoundPool
    private lateinit var audioAttributes: AudioAttributes
    private var soundStart = 0
    private var soundEnd = 0

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        (binding.recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
        binding.recyclerView.adapter = billAdapter

        observe()
        onClick()
        requestData()

        // 领取声音提示
        audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .build()

        mSoundPool = SoundPool.Builder()
            .setMaxStreams(3)
            .setAudioAttributes(audioAttributes)
            .build()

        soundStart = mSoundPool.load(mContext.assets.openFd("start.mp3"), 1)
        soundEnd = mSoundPool.load(mContext.assets.openFd("end.mp3"), 1)
    }

    private fun observe() {
        viewModel.defUI.msgEvent.observe(this) {
            when (it.msg) {
                EventConstants.UPDATE_BILL_COUNT -> {
                    binding.btnCheckboxSubmit.text =
                        "领取(" + billAdapter.getSelectedPosition().size + ")"
                }
            }
        }
        viewModel.errorResponse.observe(this) {
            handleErrorResponse(it)
            hideLoadingDialog()
        }
        //取货物品信息
        viewModel.getSpdByQhmResponse.observe(this) {
            hideLoadingDialog()
            billAdapter.clearSelectedPosition()
            billAdapter.setList(it.slwpList)
        }
        viewModel.updateSpdByQhmResponse.observe(this) {

        }
    }

    private fun onClick() {
        //返回
        binding.actionBarBack.clickNoRepeat {
            navigateBack()
        }
        // 领取
        binding.btnCheckboxSubmit.clickNoRepeat {
            receiveGoods()
        }
        // 全选
        binding.ivCheckAll.clickNoRepeat {
            billAdapter.selectAll(object : BillAdapter2.OnSelectAllListener {
                override fun onResult(all: Boolean) {
                    binding.ivCheckAll.setImageResource(if (all) R.drawable.icon_checkbox_checked else R.drawable.icon_checkbox_normal)
                    binding.btnCheckboxSubmit.text =
                        "领取(" + billAdapter.getSelectedPosition().size + ")"
                }
            })
        }
    }

    private fun receiveGoods() {
        if (billAdapter.getSelectedPosition().isEmpty()) {
            toast("请选择物品")
            return
        }
        mSoundPool.play(soundStart, 1F, 1F, 0, 0, 1F)
        for (item in billAdapter.getSelectedPosition()) {
            val bean = billAdapter.data[item]
            ModbusManager.openCase4Receive(bean.wpbh, bean.slsl, object : WriteRegistersCallback {
                override fun onSuccess() {

                }
            })
            var flag = 1
            while (flag == 1) {
                ModbusReq.getInstance().readHoldingRegisters(object : OnRequestBack<ShortArray?> {
                    override fun onSuccess(data: ShortArray?) {
                        if (data != null) {
                            if (0.equals(Integer.parseInt(data.get(0).toString())) &&
                                0.equals(Integer.parseInt(data.get(1).toString())) &&
                                0.equals(Integer.parseInt(data.get(2).toString()))
                            ) {
                                mSoundPool.play(soundEnd, 1F, 1F, 0, 0, 1F);
                                flag = 0
                            }
                        }
                    }

                    override fun onFailed(msg: String) {
                        toast(("$msg"))
                    }
                }, 1, 0, 8)
                Thread.sleep(500)
            }
//            viewModel.updateGoodsInfo(
//                "${bean.parunid}",
//                "${bean.wpbh}",
//                "${bean.unid}"
//            )
            //接口4
            viewModel.updateSpdByQhm(qhm)
        }
        ReceiveSuccessDialog.Builder(mContext)
            .setListener(object : ReceiveSuccessDialog.OnButtonClickListener {
                override fun onBackClick() {
                    navigateBack()
                    viewModel.defUI.msgEvent
                        .postValue(Message(0, EventConstants.BACK_HOME))
                }

                override fun onContinueClick() {
                    requestData()
                }
            }).show()

    }

    private fun requestData() {
        showLoadingDialog()
        //接口3
//        viewModel.getSpdByQhm(qhm)
    }

    private var loadingDialog: QMUITipDialog? = null

    private fun showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = QMUITipDialog
                .Builder(mContext)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .create()
        }
        loadingDialog?.show()
    }

    private fun hideLoadingDialog() {
        loadingDialog?.dismiss()
    }
}